package com.lancoo.answer.view.fragment.fill

import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvViewFillBinding
import com.lancoo.answer.helper.answer.FillAnswerDialog
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.Item
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.eventBean.FillAnswerEventBean
import com.lancoo.answer.view.base.BaseVMFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by Dadong on 2021/12/19
 * Describe: 填空题作答控件 小题抽题 sortIndexType = 0
 */
class FillChildFragment : BaseVMFragment<EvViewFillBinding>() {

    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var childIndex = 0
    private var defaultLoadIndex = 0
    private var itemSortIndex: String = "" //当前选择的序号
    private var currentIndex = 0
    private var sortIndexType = "0" //抽题方式 0:小题抽题 1:答题点抽题

    override fun initView(view: View) {
        EventBus.getDefault().register(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_view_fill
    }

    companion object {
        fun loadFragment(
            typeIndex: Int,
            quesIndex: Int,
            childIndex: Int,
            defaultLoadIndex: Int
        ): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_CHILDINDEX, childIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val fillChildFragment = FillChildFragment()
            fillChildFragment.arguments = mBundle
            return fillChildFragment
        }
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        childIndex = requireArguments().getInt(AnswerConstant.KEY_CHILDINDEX)
        var loadChildIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        Log.e("填空题", "loadChildIndex:" + loadChildIndex + "childIndex:" + childIndex)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        if (TextUtils.equals(ques.ChildList!![childIndex].SortIndexType!!, "1")) {
            childIndex = ques.currentLoadChildIndex
            Log.e("填空题1", "1018:" + childIndex)
        } else {
            Log.e("填空题2", "1018:" + childIndex)
        }
        defaultLoadIndex = ques.ChildList!![childIndex].currentLoadItemIndex
        itemSortIndex =
            ques.ChildList!![childIndex].ItemList!![defaultLoadIndex].ItemSortIndex!!
        sortIndexType = ques.ChildList!![childIndex].SortIndexType!!
        setInteractWebView()
    }

    //加载题干
    private fun setInteractWebView() {
        var askBody = ""
        if (sortIndexType == "0") {
            var sortIndex = ques.ChildList!![childIndex].ItemList?.get(0)?.SortIndex
            askBody = ques.ChildList!![childIndex].ChildAsk!!.replaceFirst(
                ">",
                "><div id=\"znbkflag${sortIndex}\" style=\"display:none\" class=\"znbkflag\"></div>${sortIndex}. "
            )
            mBinding.interactWv.isIndentation = false
        } else {
            askBody = ques.ChildList!![childIndex].ChildAsk!!
            mBinding.interactWv.isIndentation = true
        }
        mBinding.interactWv.setDisableInterceptTouch(sortIndexType == "0")
        mBinding.interactWv.initWebView(
            requireActivity(),
            askBody!!,
            object : InteractWebView.Callback {
                override fun finishCallback() {
                    mBinding.interactWv.showOrHideAnalysisButton(0)
                    Log.e("填空题1", "itemSortIndex:" + itemSortIndex)
                    wvLoadUrl(itemSortIndex)
                    adjustFontSize()
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(itemSortIndex)
//                    wvLoadUrl(itemSortIndex)
                    showTest()

                }
            }
        )
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    //答题点下划线，高亮等等绘制
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.interactWv.scrollPosition(position)
        when (sortIndexType) {
            "0" -> { //小题抽题
                if (ques.ChildList!!.size > 1) {
                    dealMoreFill(position)
                } else {
                    dealOneFill(position)
                }
            }

            "1" -> { //答题点抽题
                ques.ChildList!![childIndex].ItemList!!.forEachIndexed { index, item ->
                    mBinding.interactWv.loadUrl(
                        item,
                        position == item.ItemSortIndex.toString()
                    )
                    if (position == item.ItemSortIndex.toString()) {
                        currentIndex = index
                    }
                }
            }
        }
    }

    //小题抽题一题一空
    private fun dealOneFill(position: String) {
        ques.ChildList!!.forEachIndexed { index, child ->
            if (child.ItemList!!.size > 1) {
                child.ItemList!!.forEachIndexed { index, item ->
                    mBinding.interactWv.loadUrl(
                        item,
                        position == item.ItemSortIndex.toString()
                    )
                    if (position == item.ItemSortIndex.toString()) {
                        currentIndex = index
                    }
                }
            } else {
                mBinding.interactWv.loadUrl(
                    Item().apply {
                        this.StuAnswer = child.ItemList!![0].StuAnswer
                        this.ItemAnswer = child.ItemList!![0].ItemAnswer
                        this.ItemSortIndex = child.ItemList!![0].ItemSortIndex
                        this.ScoreRate = child.ItemList!![0].ScoreRate
                    },
                    position == child.ItemList!![0].ItemSortIndex
                )
                if (position == child.ItemList!![0].ItemSortIndex) {
                    currentIndex = index
                }
            }
        }
    }

    //小题抽题的一题多空
    private fun dealMoreFill(position: String) {
        ques.ChildList!!.forEachIndexed { childIndex, child ->
            //兼容一题多空（ItemList 大于1）
            if (child.ItemList!!.size > 1) {
                child.ItemList!!.forEachIndexed { itemIndex, item ->
                    mBinding.interactWv.loadUrl(
                        item,
                        position == item.ItemSortIndex.toString()
                    )
                    if (position == item.ItemSortIndex.toString()) {
                        currentIndex = itemIndex
                    }
                }
            } else {
                mBinding.interactWv.loadUrl(
                    Item().apply {
                        this.StuAnswer = child.ItemList!![0].StuAnswer
                        this.ItemAnswer = child.ItemList!![0].ItemAnswer
                        this.ItemSortIndex = child.ItemList!![0].SortIndex
                        this.ScoreRate = child.ItemList!![0].ScoreRate
                    },
                    position == child.ItemList!![0].SortIndex
                )
                if (position == child.ItemList!![0].SortIndex) {
                    currentIndex = 0
                }
            }
        }
    }

    private fun showTest() {
        FillAnswerDialog.launchFillAnswerDialog(
            requireParentFragment(),
            typeIndex, quesIndex, childIndex, currentIndex
        )
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEventMainThread(bean: FillAnswerEventBean) {
        val isCurrentChildIndex = bean.childIndex == bean.lastChidIndex
        Log.e("听力题", "进来啦")
        if (typeIndex == bean.typeIndex) {
            when (sortIndexType) {
                "0" -> { //小题
                    //专门适配句子填空一题多空的情况 todo 这个GenreId 是有问题的 ，应该是数字
                    if (ques.GenreID == "N") {
                        if (childIndex == bean.childIndex) { //用于childList大于1的判断
                            getItemSortIndex(bean.itemIndex)
                            wvLoadUrl(itemSortIndex)
                            Log.e("听力题", "进来啦$itemSortIndex")
                        }
                    } else {
                        if (childIndex == bean.childIndex && quesIndex == bean.quesIndex) {
                            getItemSortIndex(bean)
                            wvLoadUrl(itemSortIndex)
                        }
                        Log.e("听力题", "进来啦$itemSortIndex")
                    }
                }

                "1" -> { //答题点
                    Log.e("听力题", "进来啦$itemSortIndex")
                    getItemSortIndex(bean.itemIndex)
                    wvLoadUrl(itemSortIndex)
                    if (bean.quesIndex != quesIndex) {//切换大题
                    }
                }
            }
        }
        Log.e("填空题2", "itemSortIndex:" + itemSortIndex)
    }

    private fun getItemSortIndex(index: Int) {
        when (sortIndexType) {
            "0" -> { //小题
                itemSortIndex = if (ques.ChildList!!.size > 1) {
                    if (ques.ChildList!![childIndex].ItemList!!.size > 1) {
                        ques.ChildList!![childIndex].ItemList!![index].ItemSortIndex!!
                    } else {
                        ques.ChildList!![childIndex].ItemList!![0].SortIndex!!
                    }
                } else {
                    ques.ChildList!![childIndex].ItemList!![index].ItemSortIndex!!
                }
            }

            "1" -> { //答题点
                itemSortIndex = ques.ChildList!![childIndex].ItemList!![index].ItemSortIndex!!
            }
        }
    }

    private fun getItemSortIndex(bean: FillAnswerEventBean) {
        when (sortIndexType) {
            "0" -> { //小题
                itemSortIndex = if (ques.ChildList!!.size > 1) {
                    if (ques.ChildList!![childIndex].ItemList!!.size > 1) {
                        ques.ChildList!![childIndex].ItemList!![bean.itemIndex].ItemSortIndex!!
                    } else {
                        ques.ChildList!![childIndex].ItemList!![0].SortIndex!!
                    }
                } else {
                    ques.ChildList!![childIndex].ItemList!![bean.itemIndex].ItemSortIndex!!
                }
            }

            "1" -> { //答题点
                itemSortIndex =
                    ques.ChildList!![childIndex].ItemList!![bean.itemIndex].ItemSortIndex!!
            }
        }
    }

    public fun updateKeyboardShowState(isShow: Boolean) {
        Handler().postDelayed({
            mBinding.interactWv.scrollPosition(itemSortIndex)
        }, 300)
    }

    /**
     * 点击答题卡跳转对接
     */
    fun jump(index: Int) {
        Log.e("2022121301", "FillChildFragment jump" + index)
        if (ques == null) {
            return
        }
        getItemSortIndex(index)
        wvLoadUrl(itemSortIndex)
    }

    /**
     * 获取当前答题点下标
     */
    fun getCurrentIndex(): Int {
        return if (sortIndexType == "0") {
            0
        } else {
            currentIndex
        }
    }

    fun adjustFontSize() {
        if (mBinding.interactWv != null) {
            mBinding.interactWv.setFontSize()
        }
    }

    fun markQuestion() {
        var isShow = 0
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    isShow = if (item.itemMark) { //反着来
                        0
                    } else {
                        1
                    }
                    item.itemMark = !item.itemMark
                }
            }
        }
        val flagIndex = "znbkflag${itemSortIndex}"
        mBinding.interactWv.showFlag(flagIndex, isShow)
    }
}